<template>
  <div>
    <el-dialog title="监控列表" :visible.sync="dialogVisible" v-if="dialogVisible" :before-close="closeAddDialog"
      :modal-append-to-body="false" :close-on-click-modal="false" :modal="true">
      <span slot="title" class="dialog-title">
        <div class="title">监控列表</div>
      </span>
      <!-- <div class="header">
        <div class="header_box">
          <el-button size="mini" type="primary" @click="onChange()" v-preventReClick="1000">全 屏</el-button>
        </div>
      </div> -->
      <div class="main" id="camara">
        <el-row style="overflow: auto">
          <el-col :span="list.length == 1 ? 24 : list.length <= 4 ? 12 : 8" v-for="(item, index) in list" :key="index"
            :style="{
              height:
                list.length == 1
                  ? '100%'
                  : list.length == 2
                    ? '100%'
                    : list.length <= 4
                      ? '49.9%'
                      : '33.33333%',
            }">
            <!-- @click="videoDetails(item)" -->
            <div class="camara_box">
              <div :id="`265Player2${item.deviceId}`" class="camara_video"></div>
              <div class="spaceName">
                <div>安装点：{{ item.spaceName }}</div>
                <div>{{ item.deviceId }}</div>
              </div>
              <!-- <div class="none">加载中</div> -->
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetCamera } from "@api/api.js";
import screenfull from "screenfull";
import one from "@assets/images/one-screen.png";
import four from "@assets/images/four-screen.png";
import six from "@assets/images/six-screen.png";
import nine from "@assets/images/twelve-screen.png";
export default {
  data() {
    return {
      dialogVisible: false,
      one: one,
      four: four,
      six: six,
      nine: nine,
      span: 8,
      camaraNums: 6,
      isFullFlag: false,

      // 摄像头
      player: null,
      playerEZUIKit: null,
      codec: 1,
      isPause: true,
      token: "",

      list: [],
      t: null,
      i: 0,
      timer: null,

      currentPage: 0,
      totalPage: 0,
    };
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        // this.GetCamera("1583020697800630273");
      } else {
        this.t &&
          this.t
            .loginOut(this.token)
            .then((res) => {
              // console.log(res);
            })
            .catch((err) => {
              console.log(err);
            });
      }
    },
  },
  mounted() {
    // 监听页面全屏
    window.addEventListener("fullscreenchange", (e) => {
      console.log(screenfull.isFullscreen);
      this.isFullFlag = screenfull.isFullscreen;
    });
  },
  methods: {
    videoDetails(e) {
      this.$emit("onvideoDetails", e);
    },
    // 安装点查询摄像头
    async GetCamera(spaceId) {
      let res = await reqGetCamera(spaceId);
      // if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.list = res.data.row || [];
      this.list = this.list.filter((item) => item.classMark == "V380" || item.protocol == "4"); //只添加宏视  ||萤石云
      this.list.forEach(item => {
        if (item.protocol == "4") {
          item.deviceId = item.imei.slice(-8)
        }
      })
      if (this.list.length == 1) {
        this.span = 24;
      }
      await this.init(this.list);
      await this.gettoken()
    },

    // 上一页
    onPre(e) {
      this.currentNums = this.currentPage * e;
      let list2 = this.list.slice(
        this.currentNums - this.camaraNums,
        this.currentNums - this.camaraNums
      );
      this.i = 0;
      this.currentPage--;
      this.init(this.list2);
    },
    // 下一页
    onNext(e) {
      this.currentNums = this.currentPage * e;
      if (this.list.length > this.currentNums) {
        let list2 = this.list.slice(
          this.currentNums,
          this.list.length >= this.currentNums + e
            ? this.currentNums + e
            : this.list.length
        );
        console.log(
          this.currentNums,
          this.list.length >= this.currentNums + e
            ? this.currentNums + e
            : this.list.length,
          list2,
          "list2"
        );
        this.i = 0;
        this.currentPage++;
        this.init(this.list2);
      }
    },
    onChange(e) {
      this.clickFun();
    },
    // 摄像头
    init() {
      this.t = new Api();
      this.t
        .login("yuanliu@hongshi.com", "yuanliuhongshi")
        .then((res) => {
          // console.log(res);
          if (res.result == 0) {
            this.token = res.token;
            // 获取设备列表
            this.t
              .getDeviceList(res.token)
              .then((res) => {
                if (res.result == 0) {
                  this.server_ip = res.server_ip;
                  // this.playAddress(this.i);
                  this.getPlay()
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 播放视频
    getPlay() {
      this.list.forEach(async item => {
        if (item.classMark == 'V380') {
          // 宏视
          this.playAddress(item.deviceId)
        }
      })
    },
    // 播放视频
    getPlay2() {
      this.list.forEach(async item => {
        if (item.protocol == '4') {
          // 萤石云
          this.getaddress(item)
        }
      })
    },
    async playAddress(deviceId) {
      console.log(deviceId, "deviceId");
      let _this = this;
      this.t
        .requestPlayAddress(
          this.token,
          deviceId,
          this.server_ip,
          0
        )
        .then((res) => {
          if (res.code === 1000) {
            _this.codec = res.codec;
            _this.play_token = res.play_token;
            let width = res.width;
            let height = res.height;
            this.player = this.t.init(
              _this.codec,
              _this.server_ip,
              _this.play_token,
              width,
              height
            );
            this.player.play(`265Player2${deviceId}`, true);//播放事件
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 萤石云
    // 获取token
    gettoken() {
      fetch(`https://open.ys7.com/api/lapp/token/get?appKey=d6a1a4287b9a4d78adebaa7bbc8c7125&appSecret=6b9102e6b4ef80beb7067be13d08bd2c`, {
        method: "POST",
      })
        .then(response => response.json())
        .then(res => {
          // console.log(res);
          this.accessToken = res.data.accessToken;
          this.getPlay2()
        });
    },
    // 获取播放地址接口
    getaddress(data) {
      fetch(`https://open.ys7.com/api/lapp/v2/live/address/get?accessToken=${this.accessToken}&deviceSerial=${data.sn}&supportH265=1&quality=2`, {
        method: "POST",
      })
        .then(response => response.json())
        .then(res => {
          console.log(res, "data.imei");
          console.log(this.accessToken, "this.accessToken");
          this.$notify.closeAll();
          if (res.code != 200) return 
          // this.$modal.notifyWarning(res.msg);
          let playerEZUIKit = new EZUIKit.EZUIKitPlayer({
            id: `265Player2${data.imei.slice(-8)}`, // 视频容器ID
            accessToken: this.accessToken,
            url: res.data.url,
            useHardDev: true, //开启高性能模式
            template: "44d2c3c3a41a461da5f7a2c925ca1d28",
            // simple - 极简版; pcLive-pc直播；pcRec-pc回放；mobileLive-移动端直播；mobileRec-移动端回放;security - 安防版;voice-语音版;
            plugin: ['talk'], // 加载插件，talk-对讲
            // width: '100%',
            // height: '100%',
          });
          if (playerEZUIKit) {
            this.stopPromiseshow = false;
          }
          this.playerEZUIKit = playerEZUIKit;
        });
    },

    // 消控室 视频监控播放逻辑-----------------------
    async GetCamera2(frontDeviceRelatedVO) {
      this.list = frontDeviceRelatedVO
      // await this.init(this.list);
      await this.gettoken2()
    },

    // 获取token
    gettoken2() {
      fetch(`https://open.ys7.com/api/lapp/token/get?appKey=d6a1a4287b9a4d78adebaa7bbc8c7125&appSecret=6b9102e6b4ef80beb7067be13d08bd2c`, {
        method: "POST",
      })
        .then(response => response.json())
        .then(res => {
          // console.log(res);
          this.accessToken = res.data.accessToken;
          this.getPlay3()
        });
    },

    // 播放视频
    getPlay3() {
      this.list.forEach(async item => {
        if (item.protocol == '4') {
          // 萤石云
          this.getaddress2(item)
        }
      })
    },

    // 获取播放地址接口
    getaddress2(data) {
      fetch(`https://open.ys7.com/api/lapp/v2/live/address/get?accessToken=${this.accessToken}&deviceSerial=${data.sn}&supportH265=1&quality=2`, {
        method: "POST",
      })
        .then(response => response.json())
        .then(res => {
          console.log(res, "data.imei");
          console.log(this.accessToken, "this.accessToken");
          this.$notify.closeAll();
          if (res.code != 200) return 
          // this.$modal.notifyWarning(res.msg);
          let playerEZUIKit = new EZUIKit.EZUIKitPlayer({
            id: `265Player2${data.deviceId.slice(-4)}`, // 视频容器ID
            accessToken: this.accessToken,
            url: res.data.url,
            useHardDev: true, //开启高性能模式
            template: "44d2c3c3a41a461da5f7a2c925ca1d28",
            // simple - 极简版; pcLive-pc直播；pcRec-pc回放；mobileLive-移动端直播；mobileRec-移动端回放;security - 安防版;voice-语音版;
            plugin: ['talk'], // 加载插件，talk-对讲
            // width: '100%',
            // height: '100%',
          });
          if (playerEZUIKit) {
            this.stopPromiseshow = false;
          }
          this.playerEZUIKit = playerEZUIKit;
        });
    },

    // async playAddress(i) {
    //   console.log(i, "iiii");
    //   let _this = this;
    //   this.t
    //     .requestPlayAddress(
    //       this.token,
    //       this.list[i].deviceId,
    //       this.server_ip,
    //       1
    //     )
    //     .then((res) => {
    //       if (res.code === 1000) {
    //         _this.codec = res.codec;
    //         _this.play_token = res.play_token;
    //         let width = res.width;
    //         let height = res.height;
    //         this.player = this.t.init(
    //           _this.codec,
    //           _this.server_ip,
    //           _this.play_token,
    //           width,
    //           height
    //         );
    //         if (i < this.list.length - 1) {
    //           this.player.play(`265Player2${_this.i}`, true).then(() => {
    //             _this.playAddress(++_this.i);
    //           });
    //         } else {
    //           this.player.play(`265Player2${_this.i}`, false);
    //         }
    //       } else {
    //         if (i < this.list.length - 1) {
    //           _this.playAddress(++_this.i);
    //         }
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // },

    // 全屏
    clickFun() {
      this.isFullFlag = !this.isFullFlag;
      const element = document.getElementById("camara"); //指定全屏区域元素
      if (this.isFullFlag) {
        // screenfull.request(element);
        element.requestFullscreen();
      } else {
        document.exitFullscreen();
      }
    },
    closeAddDialog() {
      this.dialogVisible = false;
      if (this.playerEZUIKit) {
        this.destroy()//销毁播放器
      }
    },
    // 销毁
    destroy() {
      var stopPromise = this.playerEZUIKit.stop();
      stopPromise.then((data) => {
        // console.log("promise 获取 数据", data);
      });
    },
    // 页码判断
    onPage(e) {
      if (this.list.length) {
        switch (e) {
          case 2:
            this.i = 0;
            this.currentPage = 1;
            this.totalPage = this.list.length;
            if (this.list.length >= 1) {
              this.init(this.list[0]);
            }
            break;
          case 3:
            this.i = 0;
            this.currentPage = 1;
            this.totalPage = Math.ceil(this.list.length / 4);
            if (this.list.length >= 4) {
              let list2 = this.list.slice(0, 4);
              this.init(this.list2);
            } else if (this.list.length < 4) {
              this.init(this.list);
            }
            break;
          case 4:
            this.i = 0;
            this.currentPage = 1;
            this.totalPage = Math.ceil(this.list.length / 6);
            if (this.list.length >= 6) {
              let list2 = this.list.slice(0, 6);
              this.init(this.list2);
            } else if (this.list.length < 6) {
              this.init(this.list);
            }
            break;
          case 5:
            this.i = 0;
            this.currentPage = 1;
            this.totalPage = Math.ceil(this.list.length / 9);
            if (this.list.length >= 9) {
              let list2 = this.list.slice(0, 9);
              this.init(this.list2);
            } else if (this.list.length < 9) {
              this.init(this.list);
            }
            break;
          case 6:
            if (this.currentPage == 1) return;
            this.player = null;
            this.onPre(this.camaraNums);
            break;
          case 7:
            if (
              this.currentPage >= Math.ceil(this.list.length / this.camaraNums)
            )
              return;
            this.player = null;
            this.onNext(this.camaraNums);
        }
      }
    },
  },
};
</script>

<style scoped lang="less">
.header {
  width: 100%;
  display: flex;
  justify-content: right;

  .header_box {
    display: flex;
    align-items: center;

    .img {
      width: 22px;
      height: 22px;
      margin-left: 10px;
      cursor: pointer;

      &:hover {}
    }
  }
}

.main {
  border: 1px solid #cfd3ec38;
  width: 100%;
  margin-top: 10px;
  height: 70vh;

  display: flex;

  .camara_box {
    height: 100%;
    background: black;
    position: relative;
    width: 100%;
    border: 1px solid #cccccc73;
    box-sizing: border-box;

    // 萤石云
    .camara_video {
      z-index: 1;
      width: 100%;
      height: 100%;
    }

    .spaceName {
      color: #e9e9e9;
      position: absolute;
      top: 4%;
      left: 4%;
      z-index: 2;
    }

    .deviceId {
      color: #e9e9e9;
      position: absolute;
      top: 9%;
      left: 4%;
      z-index: 2;
    }

    .none {
      color: #cfd3ec38;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 0;
    }
  }

  .el-row {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;
  }
}

.title {
  color: #4eaef2 !important;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  margin-left: 6px;
}

.dialog-title {
  display: flex;
  justify-content: center;
  width: 100%;
}

::v-deep .el-dialog__body {
  //   background: #061a5e !important;
  //   opacity: 0.8;
  background: none !important;
  // min-height: 552px;
  min-height: 76vh;
  overflow-y: auto;
  padding: 20px !important;
  color: #f1f1f1;
}

::v-deep .el-dialog {
  // border: 2px solid #06b1e7;
  //box-shadow: 0px 0px 10px #06b1e7;
  width: 90%;
  overflow-y: auto;
  min-height: 76vh;
}
</style>
